package cy.jsonview.listener;
import cy.jsonview.code.Tool;
import cy.jsonview.code.Common;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;

import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
/**
 * 
 * @author zyd
 *
 */

public class OrderNodeActionListener implements ActionListener{
	private int model;
	private JTree tree;
	private Map jsonEleTreeMap;
	/**
	 * 
	 * @param model:0表示原序排序，1表示正序排序，2表示倒序排序
	 * @param tree
	 * @param jsonEleTreeMap
	 */
	public OrderNodeActionListener(int model,JTree tree,Map jsonEleTreeMap) {
		this.model= model;
		this.tree= tree;
		this.jsonEleTreeMap=jsonEleTreeMap;
	}
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		//Feature.OrderedField解决乱序问题
//        Object jsonobj = JSON.parse(text, Feature.AllowSingleQuotes, Feature.OrderedField);
//        String jsonText = JSON.toJSONString(jsonobj, SerializerFeature.WriteMapNullValue, SerializerFeature.PrettyFormat);
        
		
		Object obj=jsonEleTreeMap.get(tree.hashCode());
		DefaultMutableTreeNode root=(DefaultMutableTreeNode)tree.getModel().getRoot();
		
		//清旧数据
		if(root!=null) {
			 root.removeAllChildren();
	        }
		 
		if(model==0) {
			 if (obj instanceof JSONObject) {
	            	Tool.analyzeJsonObject((JSONObject) obj, root);
	            } else if (obj instanceof JSONArray) {
	            	Tool.analyzeJsonArray((JSONArray) obj, root, "");
	            }
		}else if(model==1) {
			if (obj instanceof JSONObject) {
            	Tool.analyzeJsonObject(Tool.getSortJson((JSONObject)obj,model), root);
            } else if (obj instanceof JSONArray) {
            	Tool.analyzeJsonArray(Tool.getSortJson((JSONArray)obj,model), root, "");
            }
			
//			Biz.analyzeJsonObject(Biz.getSortJson((JSONObject)obj,model),root );
		}else if(model==2) {
			if (obj instanceof JSONObject) {
            	Tool.analyzeJsonObject(Tool.getSortJson((JSONObject)obj,model), root);
            } else if (obj instanceof JSONArray) {
            	Tool.analyzeJsonArray(Tool.getSortJson((JSONArray)obj,model), root, "");
            }
//			Biz.analyzeJsonObject(Biz.getSortJson((JSONObject)obj,model),root);
		}
		tree.updateUI();
//		tree.update(null);
		 if(Common.EXPAND_TREE) {
         	// 展开根目录
             TreeNode node=(TreeNode)tree.getModel().getRoot();
             Tool.expandAll(tree, new TreePath(node), true);
             tree.updateUI();
         }
		
	}
}


